﻿
using AntDesign;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using System.Net.NetworkInformation;
using static System.Net.Mime.MediaTypeNames;

namespace EmployeeLeaveSystem.Server.Controllers {
    [Route("api/[controller]/[Action]")]
    [ApiController]
    public class FileController : ControllerBase {
        readonly EpMainContext _context;
        readonly string imgsPath;
        private readonly ILogger<FileController> logger;
        public String TEST() {
            return "DirPath：" + imgsPath;
        }

        public FileController(EpMainContext context, IWebHostEnvironment hostEnvironment, ILogger<FileController> logger) {
            this._context = context;
            this.imgsPath = Path.Combine(Environment.CurrentDirectory, "Imgs");
            this.logger = logger;
        }

        [HttpPost]
        public async Task<ActionResult<String>> UpLoadFile([FromForm] IEnumerable<IFormFile> files) {
            var file = files.FirstOrDefault();
            if (file == null) { Response.StatusCode = 500; return "BAD POST"; }
            Console.WriteLine($"接受到了文件上传 {file.FileName}");
            //开始保存文件
            var path = Path.Combine(Environment.CurrentDirectory, "Imgs", file.FileName);
            await using FileStream fs = new(path, FileMode.Create);
            await file.CopyToAsync(fs);
            logger.LogInformation("{FileName} saved at {Path}", file.FileName, path);
            return file.FileName;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<(string name, string url)> UpLoadImageAsync(IFormFile image) {
            var (name, url) = await SaveImgAsync(image);
            return (name, url); // 上传文件后，返回文件的名字，压入数据库
        }

        //[HttpGet]
        //public async Task<Object> DownLoadImageAsync(string fileName) {
        //    var PathStr = Path.Combine(imgsPath, fileName);
        //    if (System.IO.File.Exists(PathStr)) {

        //    } else {

        //    }
        //}

        /// <summary>
        /// Return name and url after saving
        /// </summary>
        /// <param name="Img">File</param>
        /// <param name="ImgName">FileName</param>
        /// <returns></returns>
        private async Task<(string name, string url)> SaveImgAsync(IFormFile Img, string ImgName = null) {
            if (string.IsNullOrEmpty(ImgName)) {
                ImgName = $"{Guid.NewGuid()}{Path.GetExtension(Img.FileName)}";
            }
            var PathStr = Path.Combine(imgsPath, ImgName);
            if (System.IO.File.Exists(PathStr)) {
                System.IO.File.Delete(PathStr);
            }
            using (var FileStream = System.IO.File.OpenWrite(PathStr)) {
                await Img.CopyToAsync(FileStream);
            }
            return (ImgName, $@".\Imgs\{ImgName}");
        }
    }
}
